#!/bin/bash

# 检查是否为root用户
if [[ "$(whoami)" != "root" ]]; then
  echo "请使用root用户运行此脚本。"
  exit 1
fi

# 确保脚本在遇到错误时立即退出
set -e
set -o pipefail

source ./common.sh

zookeeper_tar="$(basename ${zookeeper_package_path})"
zookeeper_orig_dir="${zookeeper_tar%.tar.gz}"
zookeeper_dir="${zookeeper_tar%-bin.tar.gz}"
zookeeper_dir="${zookeeper_dir#apache-}"

# 创建zkData目录变量
zkData_dir="zkData"

for server in "${zookeeper_servers[@]}"; do

  echo "开始安装zookeeper到 ${server}"

  # 复制安装包
  if [ "${server}" != "${master_server}" ]; then
    sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${master_server}" "rsync -av ${zookeeper_package_path}  ${new_user}@${server}:${software_directory}"
  fi

  # 删除已存在的目录
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "sudo rm -rf /opt/module/zookeeper*"

  # 解压缩到module_path目录下
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "tar -zxf ${software_directory}${zookeeper_tar} -C ${module_path}/"

  # 修改名称
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "mv ${module_path}/${zookeeper_orig_dir}/ ${module_path}/${zookeeper_dir}/"

  # 创建zkData目录
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "mkdir -p  ${module_path}/${zookeeper_dir}/${zkData_dir}/"

  # 配置myid文件
  server_id="${server: -1}"
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "echo \"${server_id}\" > ${module_path}/${zookeeper_dir}/${zkData_dir}/myid"

  # 配置zoo.cfg文件
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "mv ${module_path}/${zookeeper_dir}/conf/zoo_sample.cfg ${module_path}/${zookeeper_dir}/conf/zoo.cfg"
  dataDir_line=$(sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "grep -n 'dataDir=' ${module_path}/${zookeeper_dir}/conf/zoo.cfg | cut -f1 -d:")
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "sed -i \"${dataDir_line}d\" ${module_path}/${zookeeper_dir}/conf/zoo.cfg"
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "sed -i \"${dataDir_line}i\\dataDir=${module_path}/${zookeeper_dir}/${zkData_dir}\" ${module_path}/${zookeeper_dir}/conf/zoo.cfg"

  # 将cluster配置追加到文件末尾
  for zk_server in "${zookeeper_servers[@]}";
  do
	id="${zk_server: -1}"
	sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "echo "server.${id}=${zk_server}:2888:3888" >> ${module_path}/${zookeeper_dir}/conf/zoo.cfg"
  done
done

echo "zookeeper安装完成"